<template>
  <Select
    v-model="currValue"
    filterable
    remote
    ref="store"
    :loading="loading"
    clearable
    :remote-method="remote"
    @on-clear="remote">
    <Option v-for="(item, index) in storeList" :value="item.id" :key="index">{{item.label}}</Option>
  </Select>
</template>
<script>
  import { debounce } from '@/util'
  export default {
    props: {
      value: {
        type: [String, Number],
        default: null
      },
      provinceId: {
        type: [String, Number],
        default: null
      },
      cityId: {
        type: [String, Number],
        default: null
      },
      areaId: {
        type: [String, Number],
        default: null
      },
      distributorId: {
        type: [String, Number],
        default: null
      },
      src: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        storeList: [],
        loading: false,
        oTimerDetail: null,
        first: 1
      }
    },
    computed: {
      currValue: {
        get() {
          return this.value
        },
        set(v) {
          this.$emit('input', v || '')
        }
      }
    },
    mounted() {
      this.getDetailData()
    },
    methods: {
      onchange(val) {
        this.$emit('onchange', val)
      },
      remote(query='') {
        this.getDetailData(query)
      },
      getDetailData: debounce(function d(query='') {
        this.loading = true
        let param = {
          provinceId: this.provinceId,
          cityId: this.cityId,
          areaId: this.areaId,
          distributorId: this.distributorId
        }
        if (this.first === 1) {
          param.storeId = this.value ? this.value : null
          param.searchWord = null
        } else {
          param.storeId = null
          param.searchWord = query
        }
        return this.$ajaxGet(this.src, param).then(data => {
          this.first = 2
          this.loading = false
          this.storeList = []
          this.storeList = (data.records || []).map(item => {
            return {
              id: item.storeId,
              label: item.storeName
            }
          })
        })
      }, 400)
    },
    watch: {
      currValue(v) {
        this.$emit('input', v)
      },
      value(v) {
        this.currValue = v
      }
    }
  }
</script>